/**
 * Created by Weizehua on 2017/2/19.
 */
import {HandlerClass, Handle, ParamType, Require, Validators} from "../Core/Dispatcher/Dispatcher";
import {Connection} from "typeorm";
import {UserInfo} from "./UserInfo";
import {isLogged} from "../User/UserHandler";
import {User} from "../User/User";
import {RequestUserInfo} from "../Core/Dispatcher/Types";
import {VerifyUpload} from "../Core/Dispatcher/Shortcut";
import {MinLen, MaxLen} from "../Core/Validator/Length";
@HandlerClass()
export class UserInfoHandler {

    constructor(protected typeorm: Connection) {
    }

    @Handle('/user/info/change')
    @ParamType({
        nickname: String,
        uploadInfo: {url: String,},
    })
    @VerifyUpload()
    @Validators({
        nickname: [MinLen(2), MaxLen(10)]
    })
    @Require(isLogged)
    async changeUserInfoHandler(userInfo: RequestUserInfo, param: any) {
        let userId = userInfo.id;
        let info = await this.typeorm.entityManager.findOne(UserInfo, {user: userId});
        info.user = {id: userId} as User;
        info.nickname = param.nickname;
        info.headUrl = param.uploadInfo.url;
        await this.typeorm.entityManager
            .persist(info);
        return true;
    }

    @Handle('/user/info/changeNick')
    @ParamType({
        nickname: String,
    })
    @Validators({
        nickname: [MinLen(2), MaxLen(10)]
    })
    @Require(isLogged)
    async changeUserNickNameHandler(userInfo: RequestUserInfo, param: any) {
        let userId = userInfo.id;
        let info = await this.typeorm.entityManager.findOne(UserInfo, {user: userId});
        info.user = {id: userId} as User;
        info.nickname = param.nickname;
        await this.typeorm.entityManager
            .persist(info);
        return true;
    }
}
